package com.example.weatherapp1.provider


import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.MatrixCursor
import android.net.Uri
import android.os.CancellationSignal
import com.example.weatherapp1.data.local.WeatherDatabase
import com.example.weatherapp1.data.model.SavedWeather
import kotlinx.coroutines.runBlocking

class WeatherContentProvider : ContentProvider() {
    companion object {
        const val AUTHORITY = "com.example.weatherforecast.provider"
        const val WEATHER_PATH = "weather"
        const val WEATHER_ID = 1
        const val WEATHER_ALL = 2

        val BASE_URI: Uri = Uri.parse("content://$AUTHORITY")
        val WEATHER_URI: Uri = Uri.withAppendedPath(BASE_URI, WEATHER_PATH)

        val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {
            addURI(AUTHORITY, WEATHER_PATH, WEATHER_ALL)
            addURI(AUTHORITY, "$WEATHER_PATH/#", WEATHER_ID)
        }
    }

    private lateinit var db: WeatherDatabase

    override fun onCreate(): Boolean {
        context?.let {
            db = WeatherDatabase.getInstance(it)
            return true
        }
        return false
    }

    override fun query(
        uri: Uri,
        projection: Array<String>?,
        selection: String?,
        selectionArgs: Array<String>?,
        sortOrder: String?
    ): Cursor? {
        return query(uri, projection, selection, selectionArgs, sortOrder, null)
    }

    override fun query(
        uri: Uri,
        projection: Array<String>?,
        selection: String?,
        selectionArgs: Array<String>?,
        sortOrder: String?,
        cancellationSignal: CancellationSignal?
    ): Cursor? {
        return when (uriMatcher.match(uri)) {
            WEATHER_ALL -> getAllWeather()
            WEATHER_ID -> getWeatherById(ContentUris.parseId(uri))
            else -> null
        }
    }

    private fun getAllWeather(): Cursor? {
        return runBlocking {
            val weatherList = db.weatherDao().getWeatherHistoryByCityId(0) // 实际应用中应根据条件查询
            createWeatherCursor(weatherList)
        }
    }

    private fun getWeatherById(id: Long): Cursor? {
        return runBlocking {
            val weather = db.weatherDao().getWeatherHistoryByCityId(id.toInt())
            createWeatherCursor(weather)
        }
    }

    private fun createWeatherCursor(weatherList: List<SavedWeather>): Cursor {
        val cursor = MatrixCursor(arrayOf(
            "_id",
            "city_id",
            "temperature",
            "sky_con",
            "update_time",
            "weather_json"
        ))

        weatherList.forEach { weather ->
            cursor.addRow(arrayOf(
                weather.id,
                weather.cityId,
                weather.temperature,
                weather.skyCon,
                weather.updateTime,
                weather.weatherJson
            ))
        }

        return cursor
    }

    override fun getType(uri: Uri): String? {
        return when (uriMatcher.match(uri)) {
            WEATHER_ALL -> "vnd.android.cursor.dir/vnd.$AUTHORITY.$WEATHER_PATH"
            WEATHER_ID -> "vnd.android.cursor.item/vnd.$AUTHORITY.$WEATHER_PATH"
            else -> null
        }
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        // 实现插入逻辑（如果需要）
        return null
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
        // 实现删除逻辑（如果需要）
        return 0
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<String>?
    ): Int {
        // 实现更新逻辑（如果需要）
        return 0
    }
}
